package com.qiezikaka.kaka.utils;

import static androidx.constraintlayout.motion.utils.Oscillator.TAG;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.qiezikaka.kaka.http.HttpClient;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
    private final Thread.UncaughtExceptionHandler defaultUEH;
    private final String localPath;
    private  Context context;

    public CustomExceptionHandler(String localPath, Context context) {
        this.localPath = localPath;
        this.context = context;
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
//        writeLogToFile(throwable);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonPayload = createJsonPayload(throwable);

                Map<String, String> params = new HashMap<>();
                params.put("bbbb", jsonPayload);

                HttpClient.post("http://api.xiyou.dajunzhu.cn/site/log", params, String.class, new HttpClient.HttpResponseCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        Log.e("长传陈工","");
                        defaultUEH.uncaughtException(thread, throwable);
                    }

                    @Override
                    public void onFailure(String error) {
                        Log.e("长传失败","");
                    }
                });

//                OkHttpClient client = new OkHttpClient();
//                MediaType JSON = MediaType.get("application/json; charset=utf-8");
//
//                // Create JSON payload with the exception details
//                String jsonPayload = createJsonPayload(throwable);
//
//                RequestBody body = RequestBody.create(jsonPayload, JSON);
//                Request request = new Request.Builder()
//                        .url("http://api.xiyou.dajunzhu.cn/site/log")
//                        .post(body)
//                        .build();
//
//                try {
//                    Response response = client.newCall(request).execute();
//                    if (!response.isSuccessful()) {
//                        Log.e(TAG, "Failed to upload log: " + response.message());
//                    }
//                } catch (IOException e) {
//                    Log.e(TAG, "Failed to upload log", e);
//                }

            }
        }).start();
//
//        // Let the default handler handle the exception

//        defaultUEH.uncaughtException(thread, throwable);
    }

    private String createJsonPayload(Throwable throwable) {
        StringBuilder jsonPayload = new StringBuilder();
        jsonPayload.append("{");
        jsonPayload.append("\"date\":\"").append(new Date().toString()).append("\",");
        jsonPayload.append("\"exception\":\"").append(throwable.toString()).append("\",");
        jsonPayload.append("\"stacktrace\":\"");
        for (StackTraceElement element : throwable.getStackTrace()) {
            jsonPayload.append(element.toString()).append("\\n");
        }
        jsonPayload.append("\"}");
        return jsonPayload.toString();
    }



    private void writeLogToFile(Throwable throwable) {
        try {
            File logFile = new File(localPath, "crash_log.txt");
            if (!logFile.exists()) {
                logFile.createNewFile();
            }

            FileWriter writer = new FileWriter(logFile, true);
            writer.write(new Date().toString() + "\n");
            writer.write(throwable.toString() + "\n");

            for (StackTraceElement element : throwable.getStackTrace()) {
                writer.write(element.toString() + "\n");
            }

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
